// pages/productdetails/productdetails.js
var app = getApp()
var WxParse = require('../../wxParse/wxParse.js');
const {domain} = app.globalData;

Page({
    data: {
        domain: domain,
        tabs: ["商品详情", "商品评价"],
        sliderOffset: 0,
        sliderLeft: 0,
        activeIndex: 0,
        choiceStyleHidden: true,
        isGroupbuying: false,
        gourpbuyingSum: 0,
        groupbuyingList: [],
        groupbuyingGoods: {},
        shareTitle: '',
    },
    tabClick: function (e) {
        this.setData({
            activeIndex: e.currentTarget.id
        });
    },

    //拨打电话
    makePhone : function(){
        wx.makePhoneCall({
            phoneNumber: '18026409791',
        })
    },

    //购物车点击事件
    cartClick : function(){
        wx.switchTab({
            url: '../cart/cart',
        })
    },

    //首页点击事件
    indexClick : function(){
        wx.switchTab({
            url: '../index/index',
        })
    },

    choiceStyle: function (e) {
        var id1 = e.currentTarget.dataset.myid;
        var id2 = e.currentTarget.id;
        var style = this.data.product.style;
        for (var i = 0; i < style.length; i++) {
            for (var j = 0; j < style[i].values; j++) {
                style[i].values[j].isChoosed = 0;
            }
        }
        for (var i = 0; i < style.length; i++) {
            if (id1 == style[i].id) {
                for (var j = 0; j < style[i].values; j++) {
                    if (id2 == style[i].values[j].id) {
                        style[i].values[j].isChoosed = 1;
                    }
                }
            }
        }
        var product = this.data.product;
        product.style = style;
        this.setData({ product: product});
    },
    setStyleHidden: function () {
        this.setData({
            modelHidden : false
        })
    },
    formatDate: function (str) {
        var now = new Date(parseInt(str) * 1000);
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();

        return year + "年" + this.fixZero(month, 2) + "月" + this.fixZero(date, 2) + "日";
    },
    fixZero: function (num, length) {
        var str = "" + num;
        var len = str.length; var s = "";
        for (var i = length; i-- > len;) {
            s += "0";
        }
        return s + str;
    },

    onLoad: function (options) {
        var thiz = this
        wx.getSystemInfo({
            success: function (res) {
                thiz.setData({
                    hiddenLoading: false,
                    windowHeight: res.windowHeight,
                    windowWidth: res.windowWidth,
                    goods_id: options.goods_id,
                    modelHidden: true
                });
            }
        })
        
        thiz.setData({
            inv_i: app.globalData.inv_i
        })
        thiz.loadData();
        //thiz.loadComment()

        wx.showShareMenu({
            withShareTicket: true
        })
    },

    onShow() {
        this.data.isGroupbuying && this.getGroupbuyingList();
    },

    /*loadComment : function(key){
        var thiz = this

        var domain = app.globalData.domain
        var commentInterface = app.globalData.commentInterface
        var cid = app.globalData.cid
        var kui_key
        if (key){
            kui_key = key
        }else{
            kui_key = app.globalData.kui_key
        }

        wx.request({
            url: domain + commentInterface,
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data: {
                format_type:'json',
                api_cate:'Comment',
                api: 2007,
                c_id: cid,
                type : 'GOODS',
                p :1,
                page_size : 10000,
                target_id : thiz.data.goods_id
            },
            success : function(res){
                if(res.data.status == 1){
                    if(res.data.data.list.length > 0){
                        res.data.data.list.forEach(function(element, index){
                            element.add_time = thiz.formatDate(element.add_time)
                        })
                        thiz.setData({
                            allComment: res.data.data.list,
                            comment: res.data.data.list
                        })
                    }else{
                        thiz.setData({
                            comment: []
                        })
                    }
                }

                if (res.data.status == 0){
                    thiz.setData({
                        comment : []
                    })
                }
            }
        })
    },*/


    loadData : function(key){
      var thiz = this
      var PageInterface = app.globalData.domain + app.globalData.PageInterface
      var domain = app.globalData.domain

      var goods_amount = 1;
      //圆角显示的数量
      var total_goods_amount = 0;

      wx.request({
        url: PageInterface,
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          format_type: 'json',
          api_cate: 'Goods',
          api: 4001,
          c_id: 2,
          goods_id: 4
        },
        success: function (res) {
          if(res.data.msg){
            console.log(res)
            wx.showToast({
              title: 'res.data.errMsg',
            })
          }else{

          }
          /*if (res.data.errMsg) {
            thiz.loadData()

          } else {
            res.data.img.forEach(function (element, index) {
              element.goods_imgurl = domain + "/" + element.goods_imgurl
            })

            var active_goods_options = [];

            res.data.default_img = domain + res.data.default_img

            if (res.data.all_spec) {

              res.data.all_spec.forEach(function (element, index) {
                if (element.checked == 1) {
                  active_goods_options.push(element)
                }
              })
            }

            if (res.data.spec) {
              res.data.spec.forEach(function (element, index) {
                element.spec_item.reverse()
                element.spec_item.forEach(function (each, eachIndex) {
                  each.status = false
                })
              })
            }

            WxParse.wxParse('goods_describe', 'html', res.data.goods_describe, thiz, 0);

            total_goods_amount = thiz.cart_count();
            thiz.setData({
              hiddenLoading: true,
              active_goods_options: active_goods_options[0],
              spec_totolPrice: active_goods_options[0].price,
              goods_detail: res.data,
              activeSpec: [],
              specOption: active_goods_options.specs,
              goods_amount: goods_amount,
              total_goods_amount: total_goods_amount
            })
          }*/
        }
      });
        
    },

    contains: function (arr, id) {
        //while
        var i = arr.length;
        while (i--) {
            if (arr[i].active_goods_options.goods_option_id === id) {
                return i;
            }
        }
        return -1;
    },

    //加入购物车
    addCart : function(){
        var thiz = this

        var goods_detail = this.data.goods_detail
        var amount = this.data.goods_amount
        var active_goods_options = this.data.active_goods_options
        //圆角显示的购物车所有商品数量
        var total_goods_amount=0;
        var goods_info = {
            goods_detail: goods_detail,
            active_goods_options: active_goods_options,
            amount : amount
        }

        wx.getStorage({
            key: 'cartStorage',
            success: function(res) {
                if(res.data.length > 0){
                    var index = thiz.contains(res.data, active_goods_options.goods_option_id)
                    if (index == -1){
                        res.data.push(goods_info)
                    }else{
                        res.data[index].amount += amount
                    }
                    wx.setStorageSync('cartStorage', res.data)
                    wx.showToast({
                        title: '加入购物车成功',
                    });

                }else{

                    res.data.push(goods_info);
                    wx.setStorageSync('cartStorage', res.data)
                    wx.showToast({
                        title: '加入购物车成功',
                    })
                }
                total_goods_amount = thiz.cart_count();
                thiz.setData({
                    modelHidden: true,
                    total_goods_amount:total_goods_amount
                })
            },
        })

    },

    getOrderInfo(event) {
        const type = event.currentTarget.dataset.type;
        var goods_detail = this.data.goods_detail
        var amount = this.data.goods_amount
        var active_goods_options = this.data.active_goods_options
        goods_detail.goods_describe = ""
        var obj = {
            goods_detail: goods_detail,
            active_goods_options: active_goods_options,
            amount: amount
        }
        var obj2={
            amount:amount,
            checked:true,
            goods_option_id:active_goods_options.id,
            id:goods_detail.goods_id,
            img_url:goods_detail.default_img,
            name:goods_detail.goods_name,
            price: active_goods_options.price,
            size:active_goods_options.option_title
        };
        var postGoods=[];
        var pay_goods=[];
        postGoods.push(obj);
        pay_goods.push(obj2);
        var str = JSON.stringify(postGoods);
        var str2 = JSON.stringify(pay_goods);
        var totalPrice = amount * (type ? this.data.groupbuyingGoods.price : active_goods_options.price);

        return {
            str: str,
            str2: str2,
            totalPrice: totalPrice
        }
    },

    

    //提交订单
    postOrder : function(event){
        const type = event.currentTarget.dataset.type,
            result = type ? '&type=groupbuying'  : '';
        const {str, str2, totalPrice} = this.getOrderInfo(event);
        const isJoined = this.getGroupbuyingMember();
        if (type && isJoined) {
            wx.showToast({
                title: '你已开过团了',
            });
            return false;
        }
        wx.navigateTo({
            url: '../cartConfirm/cartConfirm?postGoods=' + str + '&pay_goods='+str2+'&totalPrice=' + totalPrice + result
        })
    },
    //关闭规格选择
    closeModal : function(){
        var thiz = this
        thiz.setData({
            modelHidden: !thiz.data.modelHidden
        })
    },
    //规格数量增加
    goodsAddClick : function(){
        var thiz = this

        thiz.data.goods_amount++

        var active_goods_options = thiz.data.active_goods_options

        var totalPrice = active_goods_options.price * thiz.data.goods_amount

        this.setData({
            spec_totolPrice: totalPrice,
            goods_amount: thiz.data.goods_amount
        })
    },
    //规格数量减少
    goodsReduceClick : function(){
        var thiz = this

        if (thiz.data.goods_amount > 1) {
            thiz.data.goods_amount--;
        }
        var active_goods_options = thiz.data.active_goods_options

        var totalPrice = active_goods_options.price * thiz.data.goods_amount

        this.setData({
            spec_totolPrice: totalPrice,
            goods_amount: thiz.data.goods_amount
        })
    },
    //规格选择
    spec_itemClick : function(e){
        var thiz = this
        var id = e.currentTarget.dataset.id
        var spec = thiz.data.goods_detail.spec

        var selectSpec_id = e.currentTarget.dataset.spec;
        var activeSpec = thiz.data.activeSpec

        spec.forEach(function(element, index){
            if (element.goods_spec_id == selectSpec_id){
                element.spec_item.forEach(function(each, eachIndex){
                    if (each.goods_item_id == id){
                        each.status = true

                    }else{
                        each.status = false
                    }
                })
            }
        })

        if (activeSpec.length > 0){

            if (thiz.containsSpec(activeSpec, selectSpec_id) == -1){
                activeSpec.push({
                    selectSpec_id: selectSpec_id,
                    id: id
                })
            }else{
                if (thiz.containsId(activeSpec, id) == -1){

                    activeSpec.splice(thiz.containsSpec(activeSpec, selectSpec_id), 1)

                    activeSpec.push({
                        selectSpec_id: selectSpec_id,
                        id: id
                    })
                }else{
                    activeSpec.splice(thiz.containsId(activeSpec, id), 1)
                }
            }
        }else{
            activeSpec.push({
                selectSpec_id: selectSpec_id,
                id : id
            })
        }

        var array = [];
        var stock,price;

        if (spec.length == 1){

            thiz.data.goods_detail.all_spec.forEach(function (element, index) {
                if (element.specs.indexOf(activeSpec[0].id) >= 0) {
                    array.push(element)
                }
            })

            thiz.data.active_goods_options = array[0]
        }

        if (activeSpec.length == 2){
            thiz.data.goods_detail.all_spec.forEach(function(element, index){
                if (element.specs.indexOf(activeSpec[0].id) >= 0){
                    if (element.specs.indexOf(activeSpec[1].id) >= 0){

                        array.push(element)
                    }
                }
            })

            thiz.data.active_goods_options = array[0]
        }



        thiz.setData({
            goods_detail: thiz.data.goods_detail,
            lastSpec: thiz.data.lastSpec,
            activeSpec: activeSpec,
            active_goods_options: thiz.data.active_goods_options,
            spec_totolPrice: thiz.data.active_goods_options.price,
            goods_amount:1
        })


    },
    containsSpec : function(arr, id) {
        //while
        var i = arr.length;
        while (i--) {
            if (arr[i].selectSpec_id === id) {
                return i;
            }
        }
        return -1;
    },
    containsId: function (arr, id) {
        //while
        var i = arr.length;
        while (i--) {
            if (arr[i].id === id) {
                return i;
            }
        }
        return -1;
    },
    cart_count: function () {
        //购物车商品数量
        var total_goods_amount=0;
        var cartStorage = wx.getStorageSync('cartStorage')
        if(cartStorage.length > 0){
            cartStorage.forEach(function (element, index) {
                total_goods_amount+=element.amount
            })
        }
        return total_goods_amount;
    }
})